package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithDishFlavor(dishDto);

        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(String name, Integer page, Integer pageSize) {
        //构造查询条件
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        //构造分页对象
        Page<Dish> pageInfo1 = new Page<>(page, pageSize);
        dishService.page(pageInfo1, queryWrapper);


        //Page<Dish> pageInfo 做数据处理
        Page<DishDto> pageInfo2 = new Page<>(page, pageSize);

        //1.将pageInfo1中的数据拷贝到pageInfo2中（分两个阶段：List，Total）（先拷贝除了records的所有数据）
        BeanUtils.copyProperties(pageInfo1, pageInfo2, "records");//除了records
        //2.将pageInfo1中的List<Dish>转为List<DishDto>（复制records）
        List<DishDto> dishDtoList = new ArrayList<>();
        //2.1遍历pageInfo1中的list集合并设置
        for (Dish dish : pageInfo1.getRecords()) {
            //    2.2将Dish转变为DishDto（也就是records的集合）
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //TODO 2.3 处理分类名称
            Category category = categoryService.getById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        //2.4 将设置好的List集合(records)添加到pageInfo2中
        pageInfo2.setRecords(dishDtoList);
        return R.success(pageInfo2);
    }

    /**
     * 根据ID查询
     */
    @GetMapping("{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        DishDto dishDto = dishService.findByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateByIdWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改成功");
    }


    /**
     * 根据分类ID查询菜品列表（套餐分类使用）
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId) {
        //动态构造key
        String key = "dish_" + categoryId;
        //先从redis中获取缓存数据
        List<DishDto> dishDtoList1 = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList1 != null) {
            //    如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList1);
        }


        //    select * from dish where category_id=?
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        queryWrapper.eq("status", "1");
        //    排序条件
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        List<Dish> dishList = dishService.list(queryWrapper);

        //添加口味
        //转换数据，将List<Dish>转换成List<DishDto>对象
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();//DishDto=Dish+DishFlavor
            //拷贝
            BeanUtils.copyProperties(dish, dishDto);
            //复制口味 select * from dish_flavor where dish_id=?
            QueryWrapper<DishFlavor> dishFlavorQueryWrapper = new QueryWrapper<>();
            dishFlavorQueryWrapper.eq("dish_id", dish.getId());
            //根据条件查询口味集合
            List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorQueryWrapper);
            //将口味集合添加到当前dishDto中
            dishDto.setFlavors(flavorList);
            //将dishDto添加到list集合中
            dishDtoList.add(dishDto);
        }

        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}